#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>

static int isClicked = 0;
static pthread_t clickThread;

int getch()
{
	struct termios oldt, newt;
	tcgetattr(STDIN_FILENO, &oldt);
	newt = oldt;
	newt.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(STDIN_FILENO, TCSANOW, &newt);
	int ret = getchar();
	tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
	return ret;
}

//TODO make a function for click, double click, and a long press and have the triggered by the apropriate action
void button_click()
{
	printf("Single click\n");
	isClicked = 0;
}

void double_click()
{
	printf("Double click\n");
	isClicked = 0;
}

struct timer_struct {
	int durration;
	void (*handler)();
};

static void* g_start_timer(void *t)
{
	struct timer_struct *ts = (struct timer_struct*)t;

	usleep(1000 * ts->durration);
	ts->handler();
	free(t);
	pthread_exit(0);
}

pthread_t after_ms_do(int durration, void (*handler)())
{
	pthread_t ret;
	struct timer_struct *t = malloc(sizeof(struct timer_struct));
	t->durration = durration;
	t->handler = handler;
	if(pthread_create(&ret, 0, &g_start_timer,(void*)t))
		return -1;
	return ret;
}

void button_event()
{
	isClicked++;
	printf("%d\n", isClicked);
	if (isClicked == 2) {
		clickThread = after_ms_do(1000, &button_click);
//		button_click();
	}
	else if (isClicked == 4){
		pthread_cancel(clickThread);
		double_click();
		isClicked = 0;
	}
}

int main(void)
{
	// initialization code goes here
	pthread_t thread1, thread2;
	char *message1 = "Thread 1";
	char *message2 = "Thread 2";
	int iret1, iret2;
//	isClicked = 0;
	printf("Press and release any key fast to emulate a button action, ctrl+c to quit.\n");
	printf("A user click would be the same a two key presses one for btn down one for btn up.\n");
	printf("A double click would be four key presses. ");
	printf("A holding the button down would be one key press a delay then a key press.\n");

	while(1)
	{
		getch();		// wait for keypress
		button_event();
	}
	return 0;
}
